<?php

namespace app\index\controller;

use app\BaseController;
use app\IndexBaseController;
use think\facade\fetch;
use think\App;
use think\facade\View;

class Paypal extends BaseController
{
    //继承
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    //支付回调
    public function returnUrl(){
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                "AW_K7gDVzvGAw1Hk9dJD3pXza486UAtYDuw0gTW8_c3L5PCaWEO8jz_JHnHJGgsnh6lqYlvBJyxlcb4c",
                "EEPatvb25Afv_uKNdpV4n4k2zR3fqI3OL_K0-iZoQCpdvVsmKvkMP0D2hzXfufpJ6Jj9xw65cJEj1bWi"
//                'AfOVF7P3q1cOdgw7WnjJQlnY3OhmJriT3YDuOEA7s-lI-2tT9cxlCXEXPdgQojlG67gGSpuS4h4BzZWr',     // ClientID
//                'EIBqhkL6ysesyxZqwD3AG9dm0mPNjfoket9MhkFSRFk5WRxpFTWfpjFlsRROhH8LKOIyYSzqyRF0HtyK'      // ClientSecret
            )
        );
        /*sandbox 模式*/
        $apiContext->setConfig(array('mode' => 'live'));


        // Get payment object by passing paymentId
        $paymentId = $this->request->param('paymentId');
        $payment = new \PayPal\Api\Payment();
        $payment = $payment->get($paymentId, $apiContext);
        $payerId = $this->request->param('PayerID');

        // Execute payment with payer ID
        $execution = new \PayPal\Api\PaymentExecution();
        $execution->setPayerId($payerId);

        try {
            // Execute payment
            $result = $payment->execute($execution, $apiContext);
            if ($result && isset ( $result->state ) && $result->state == 'approved') {
                return $this->redirectTo((string)url("/index/order_list"));
                echo "支付成功";
            }else{
                return $this->redirectTo((string)url("/index/checkout"));
                echo "支付失败";
                var_dump($result);
            }
        } catch (PayPal\Exception\PayPalConnectionException $ex) {
            echo $ex->getCode();
            echo $ex->getData();
            die($ex);
        } catch (Exception $ex) {
            die($ex);
        }
    }
    //取消支付
    public function cancelUrl(){
        return $this->redirectTo((string)url("/index/checkout"));
        echo '取消支付';
    }

}
